import type { TocItem, TocItemWithChildren } from '@/types/article.ts';

function generateToc(content: string): TocItem[] {
  const div = document.createElement('div');
  div.innerHTML = content;

  const headings = div.querySelectorAll('h1, h2, h3, h4, h5, h6');
  const toc: TocItem[] = [];

  headings.forEach((heading) => {
    const id = heading.getAttribute('id') || '';
    const text = heading.textContent || '';
    const level = parseInt(heading.tagName[1]); // 获取标题级别 h1=1, h2=2 等

    toc.push({
      id,
      text,
      level
    });
  });

  return toc;
}

export default function useGenerateTocTree(content: string): TocItemWithChildren[] {
  // 如果传入的是字符串，先生成基础目录数组
  const items = generateToc(content);

  // 如果所有项都是同一级别，直接返回一维数组
  const allSameLevel = items.every(item => item.level === items[0].level);
  if (allSameLevel) {
    return items.map(item => ({ ...item, children: [] }));
  }

  // 否则生成树形结构
  const result: TocItemWithChildren[] = [];
  const stack: TocItemWithChildren[] = [];

  items.forEach(item => {
    const node = { ...item, children: [] };

    while (stack.length && stack[stack.length - 1].level >= item.level) {
      stack.pop();
    }

    if (stack.length === 0) {
      result.push(node);
    } else {
      stack[stack.length - 1].children.push(node);
    }

    stack.push(node);
  });
  return result;
}
